const fs = require("fs");

/**
 * 解析SRT文件
 * @param {string} srtPath - SRT文件路径
 * @returns {Array} 字幕条目数组
 */
function parseSRT(srtPath) {
  const srtContent = fs.readFileSync(srtPath, "utf-8");
  const subtitles = [];
  const blocks = srtContent.split("\n\n").filter(block => block.trim() !== "");

  blocks.forEach(block => {
    const lines = block.split("\n").filter(line => line.trim() !== "");
    if (lines.length >= 3) {
      const index = lines[0];
      const timeLine = lines[1];
      const textLines = lines.slice(2);

      // 解析时间戳
      const timeMatch = timeLine.match(/(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/);
      if (timeMatch) {
        subtitles.push({
          index: parseInt(index),
          startTime: timeMatch[1],
          endTime: timeMatch[2],
          text: textLines.join("\n"),
        });
      }
    }
  });

  return subtitles;
}

/**
 * 解析SRT文件获取字幕时长信息
 * @param {string} srtFile - SRT文件路径
 * @returns {Array} 字幕数组
 */
function parseSRTWithDurations(srtFile) {
  const content = fs.readFileSync(srtFile, "utf-8");
  const blocks = content.trim().split("\n\n");

  return blocks
    .map(block => {
      const lines = block.trim().split("\n");
      if (lines.length >= 3) {
        const timeMatch = lines[1].match(/(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/);
        if (timeMatch) {
          const startTime = timeMatch[1];
          const endTime = timeMatch[2];
          const duration = srtTimeToSeconds(endTime) - srtTimeToSeconds(startTime);
          return {
            index: parseInt(lines[0]),
            startTime,
            endTime,
            duration,
            text: lines.slice(2).join("\n"),
          };
        }
      }
      return null;
    })
    .filter(item => item !== null);
}

module.exports = {
  parseSRT,
  parseSRTWithDurations,
};
